<template>
    <ClientOnly>
        <v-chart
            class="chart"
            ref="myChart"
            @datazoom="handleDataZoom"
            :manual-update="true"
            :autoresize="true"
        />
        <template #fallback>
            <!-- 这将在服务器端渲染 -->
            <MChartsSkeleton />
        </template>
    </ClientOnly>
</template>

<script setup lang="ts">
    import VChart from 'vue-echarts';

    import { loadECharts } from '@/utils/echarts';
    // chart数据
    export interface ChartItem {
        xData: string[];
        yData: string[];
    }
    loadECharts();

    const props = defineProps<{ chartData: ChartItem }>();

    const option = {
        tooltip: {
            // 当trigger为’item’时只会显示该点的数据，为’axis’时显示该列下所有坐标轴所对应的数据。
            trigger: 'axis',
            // 提示框的位置
            position: function (pt: any[]) {
                return [pt[0], '10%'];
            },
        },
        title: {
            left: 'center',
            text: '大面积量数据图',
        },
        // toolbox：这是ECharts中的工具栏。内置有导出图片、数据视图、动态类型切换、数据区域缩放、重置五个工具。
        toolbox: {
            // feature 各工具配置项: dataZoom 数据区域缩放;restore 配置项还原;saveAsImage下载为图片;magicType动态类型切换

            feature: {
                dataZoom: {
                    show: true,
                    yAxisIndex: 'none', // y轴不缩放，Index默认为0
                },
                restore: {},
                saveAsImage: {},
            },
        },
        grid: [
            {
                top: 20,
                height: 200,
            },
            {
                top: 260,
                height: 200,
            },
            {
                top: 460,
                height: 200,
            },
        ],
        axisPointer: {
            // type: 'shadow',
            link: {
                xAxisIndex: 'all',
            },
        },
        xAxis: [
            {
                type: 'category', // category为一级分类,适用于离散的类目数据
                boundaryGap: false, // 无间隙
                data: props.chartData.xData,
                gridIndex: 0,
            },
            {
                type: 'category', // category为一级分类,适用于离散的类目数据
                boundaryGap: false, // 无间隙
                data: props.chartData.xData,
                gridIndex: 1,
            },
        ],

        yAxis: [
            {
                type: 'value', // 'value' 数值轴，适用于连续数据。
                min: 0,
                max: 40,
                gridIndex: 0,
            },
            {
                type: 'value', // 'value' 数值轴，适用于连续数据。
                min: 0,
                max: 200,
                gridIndex: 1,
            },
        ],
        dataZoom: [
            {
                type: 'inside', // inside: 表示用内测滑块
                xAxisIndex: [0, 1], // 代表是作用在y轴上的
                zoomOnMouseWheel: true, // 关闭滚轮缩放
                moveOnMouseWheel: false, // 开启滚轮平移
                moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移

                startValue: 0,
                endValue: 100,
                // 最小缩放
                minSpan: 0.5,
                rangeMode: ['value'],
            },
        ],

        series: [
            {
                name: '模拟数据',
                type: 'line',
                symbol: 'none',
                // showSymbol: false,
                data: props.chartData.yData,
                xAxisIndex: 0,
                yAxisIndex: 0,

                lineStyle: {
                    width: 2,
                    borderWidth: 0,
                },
            },
            {
                name: '测试',
                type: 'line',
                symbol: 'none',
                // showSymbol: false,
                data: props.chartData.yData,
                xAxisIndex: 1,
                yAxisIndex: 1,
            },
        ],
    };

    const loading = ref(true);

    const myChart = ref<InstanceType<typeof VChart>>();

    const emit = defineEmits<{
        (e: 'loadMore'): void;
        (e: 'getChartList'): void;
    }>();

    let lastdiff = 100;
    let level = 1;
    const handleDataZoom = (event: any) => {
        // 处理datazoom事件
        console.log('Data zoom event:', event);
        if (event.batch && event.batch.length > 0) {
            let start = event.batch[0].start;
            let end = event.batch[0].end;

            let startIndex = Math.round(option.xAxis[0].data.length * (start / 100));
            let endIndex = Math.round(option.xAxis[0].data.length * (end / 100));

            let diff = Math.round(option.xAxis[0].data.length * ((end - start) / 100));

            console.log('diff', diff);
            // mircodiff > 1，说明是放大而不是拖拽
            let mircodiff = Math.abs(diff - lastdiff);
            lastdiff = diff;

            if (mircodiff !== 0) {
                if (diff < 100) {
                    // 放大之后的操作
                    console.log('放大3档');

                    getLevelList(3, start, end);
                }
                // if (diff < 50 && diff >= 20 && mircodiff > 1) {
                //     // 放大之后的操作
                //     console.log('放大2档');
                //     getLevelList(3, start, end);
                // }
                // if (diff < 75 && diff >= 50 && mircodiff > 1) {
                //     // 放大之后的操作
                //     console.log('放大1档');
                //     level = 2;
                // }
                // if (diff >= 75 && mircodiff > 1) {
                //     // 缩小回去的操作
                //     console.log('4档');
                //     level = 1;
                // }
            }

            console.log('mircodiff', mircodiff);
            if (mircodiff < 1) {
                // 拖拽操作
                if (end === 100) {
                    // 处理结束
                    console.log('拖拽到尾部');
                    emit('loadMore');
                } else if (start === 0) {
                    console.log('拖拽到头部');
                    emit('loadMore');
                }
            }
        }
    };

    const getLevelList = (changeLevel: number, start: number, end: number) => {
        // 获取级别列表
        if (level === changeLevel) {
            return;
        }
        level = changeLevel;
        console.log('start', start, 'end', end);
        let startTime = option.xAxis[0].data[Math.round(option.xAxis[0].data.length * (start / 100))];
        let endTime = option.xAxis[0].data[Math.round(option.xAxis[0].data.length * (end / 100))];
        console.log('startTime', startTime, 'endTime', endTime);
        emit('getChartList', startTime, endTime);
    };

    onMounted(() => {
        // nextTick(() => {
        //     if (myChart.value) {
        //         // 默认选中区域框选功能
        //         myChart.value.dispatchAction({
        //             type: 'takeGlobalCursor',
        //             key: 'dataZoomSelect',
        //             dataZoomSelectActive: true,
        //         });
        //         loading.value = false;
        //     }
        // });
    });

    const updateCharts = (chartData: any) => {
        if (myChart.value) {
            option.xAxis[0].data = chartData.xData;
            option.xAxis[1].data = chartData.xData;
            option.series[0].data = chartData.yData;
            option.series[1].data = chartData.yData2;

            myChart.value.setOption(option);
            // myChart.value.dispatchAction({
            //     type: 'takeGlobalCursor',
            //     key: 'dataZoomSelect',
            //     dataZoomSelectActive: true,
            // });
            // loading.value = false;
        }
    };

    defineExpose({
        updateCharts,
    });
</script>

<style scoped>
    .chart {
        height: 500px;
    }
</style>
